package com.zhangzhan.gulimallorder.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zhangzhan.gulimallorder.config.AlipayTemplate;
import com.zhangzhan.gulimallorder.service.OrderService;
import com.zhangzhan.gulimallorder.vos.PayAsyncVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/7/4 13:22
 */
@RestController
@Slf4j
public class AlipayedListener {

    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/alipayed", method = RequestMethod.POST)
    public String alipayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws  AlipayApiException {
        //从uri后面问号拼接的参数里获取全部参数
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        System.out.println(parameterMap);

        //验签：
        /**
         * @param params    待验签的从支付宝接收到的参数Map
         * @param publicKey 支付宝公钥
         * @param charset   参数内容编码集
         * @param signType  指定采用的签名方式，RSA、RSA2、SM2
         * @return true：验签通过；false：验签不通过
         * @throws AlipayApiException
         */
//        public static boolean verifyV1(Map<String, String> params, String publicKey, String charset, String signType)

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean v2 = AlipaySignature.verifyV2(params, AlipayTemplate.getAlipayConfig().getAlipayPublicKey(), AlipayTemplate.getAlipayConfig().getCharset(), AlipayTemplate.getAlipayConfig().getSignType());
        if (v2) {
            log.info("验签成功。。。。。");
            String res = orderService.alipayed(payAsyncVo);
            return res;
        } else {
            log.error("验签失败。。。。");
            return "error";
        }

    }

}
